package cn.edu.scau.cmi.liangzaoqing.filter;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;





public class ScauCmiGeneratorFilter implements Filter {
	
	public void destroy() {
	}
	
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain fc) throws IOException, ServletException {
	
		System.out.println("进入了ScauCmiGeneratorFilter");
//		把response对象封装为wrapper对象
		CharArrayWrapper wrapper = new CharArrayWrapper((HttpServletResponse) resp);

		fc.doFilter(req, wrapper);
		
			String httpResponseString = Jsp4Code.code(req, resp, wrapper);
			//将过滤了的response输出到浏览器页面					
			out2Browser(resp, httpResponseString);
			
			File file=new File("D:/jsp.java");
			FileUtils.writeStringToFile(file, httpResponseString);
		
	}
	/**
	 *将过滤了的response输出到浏览器页面
	 * @param resp
	 * @param httpResponseString
	 * @throws IOException
	 */
	private void out2Browser(ServletResponse resp, String httpResponseString)
			throws IOException {
		// 处理返回结果
		PrintWriter out = resp.getWriter();
		out.write(httpResponseString);
		out.flush();
		out.close(); // 输出处理后的结果
	}
	
	public void init(FilterConfig arg0) throws ServletException {

	}
}